package com.superb.common.redis.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.superb.common.properties.RedisConfigProperties;
import com.superb.common.utils.StringUtils;
import jakarta.annotation.Resource;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * @Author: ajie
 * @CreateTime: 2024-06-19 08:42
 */
@Configuration
public class RedisConfiguration {

    @Resource
    private RedisConfigProperties redisConfigProperties;

    @Resource
    private ObjectMapper objectMapper;

    // 添加redisson的bean
    @Bean(destroyMethod="shutdown")
    public RedissonClient redisson() {
        String redissonAddr = "redis://" + redisConfigProperties.getHost() + ":" + redisConfigProperties.getPort();
        Config config = new Config();
        config.setCodec(new JsonJacksonCodec(objectMapper));
        config.useSingleServer().setAddress(redissonAddr);
        if (StringUtils.isNotEmpty(redisConfigProperties.getPassword())) {
            config.useSingleServer().setPassword(redisConfigProperties.getPassword());
        }
        return Redisson.create(config);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        redisTemplate.setValueSerializer(RedisSerializer.json());
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }

}
